package cn.com.mrzheng.web.server.Base;

import cn.com.mrzheng.web.entity.BaseEntity;
import cn.com.mrzheng.web.mapper.base.CurdInterface;
import cn.com.mrzheng.web.utils.AutoKey;
import cn.com.mrzheng.web.utils.ErrorCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

public class BaseServiceImpl<T extends BaseEntity,J extends CurdInterface<T>> {
    @Autowired
    J database;

    ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
    Class<T> modelClass = (Class<T>) type.getActualTypeArguments()[0];

    //  获取列表
    public List<T> list (String filter, String currentPage, String pageSize) {
        // 筛选条件
        JSONObject jsonObject = JSONObject.parseObject(filter);
        Map<String,Object> map = jsonObject;

        // 分页筛选
        if (!currentPage.isEmpty() && !pageSize.isEmpty()) {
            map.put("currentPage",(Integer.parseInt(currentPage)-1) * Integer.parseInt(pageSize));
            map.put("pageSize",Integer.parseInt(pageSize));
        }

        List<T> list = database.list(map);
        return list;
    }

    // 添加修改实体
    public Integer saveEntity(String jsonEntity) {
        T javaBean = JSON.parseObject(jsonEntity, modelClass);
        int status = 0;
        if (javaBean.getId().equals("")) {
            // 新增
            javaBean.setId(AutoKey.getKey());
            status = database.addEntity(javaBean);
        } else {
            // 编辑
            status = database.updateEntity(javaBean);
        }
        return status;
    }

    // 添加修改  唯一 实体
    public Integer saveEntity(String jsonEntity,String uniqueJson) {
        T javaBean = JSON.parseObject(jsonEntity, modelClass);
        int status = 0;
        if (javaBean.getId().isEmpty() || javaBean.getId() == null) {
            // 新增
            // 筛选数据是否有重复
            List<T> list = list(uniqueJson,"1","10");
            // 数据库有数据的时候list.size>0
            if (list.size()>0){
                status = ErrorCode.REPETE;
                return status;
            } else {
                javaBean.setId(AutoKey.getKey());
                status = database.addEntity(javaBean);
            }
        } else {
            // 编辑
            status = database.updateEntity(javaBean);
        }
        return status;
    }

    // 删除
    public Integer deleteEntity(String id) {
        int status = 0;
        status = database.deleteEntity(id);
        return status;
    }

    // 查找单个数据
    public T getEntity(String id) {
        T role = null;
        role = database.getEntity(id);
        return role;
    }
}
